import { _decorator, Component, find, Label, Sprite, Node } from 'cc';
import { EventManager, MyEvent } from '../Managers/EventManager';
const { ccclass, property } = _decorator;

@ccclass('SkillButton')
export class SkillButton extends Component {
    fill: Sprite;
    label: Label;
    mask: Node;

    totalTime: number = 0;
    cooldownTime: number = 0;
    cooldownTimer: number = 0;

    protected onLoad(): void {
        this.fill = find("Mask/Fill", this.node).getComponent(Sprite);
        this.label = find("CooldownLabel", this.node).getComponent(Label);
        this.mask = find("Mask", this.node);
        this.Refresh();
    }

    Set(cooldownTime: number) {
        clearInterval(this.cooldownTimer);

        this.totalTime = cooldownTime;
        this.cooldownTime = cooldownTime;
        this.label.node.active = true;
        this.mask.active = true;

        this.Refresh();

        this.cooldownTimer = setInterval(() => {
            this.cooldownTime -= 0.1;
            this.Refresh();
            if (this.cooldownTime <= 0) {
                clearInterval(this.cooldownTimer);
                EventManager.Scene.emit(MyEvent.SKILL_COOLDOWN);
            }
        }, 100);
    }

    private Refresh() {
        this.label.string = `${Math.abs(this.cooldownTime).toFixed(1)}`;
        this.fill.fillRange = this.cooldownTime / this.totalTime;
        if (this.cooldownTime <= 0) {
            this.label.node.active = false;
            this.mask.active = false;
        }
    }
}